#include <iostream>
#include <cstring>
#include <unistd.h>

int main()
{
    int pipefd[2]; // 0是读端，1是写端
    pid_t pid;

    // 创建管道
    if (pipe(pipefd) == -1)
    {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    pid = fork();
    if (pid == -1)
    {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    if (pid > 0) // 父进程
    {
        // 关闭读端
        close(pipefd[0]);

        // 写数据到管道
        const char *msg = "Hello from parent!";
        write(pipefd[1], msg, strlen(msg));

        // 关闭写端
        close(pipefd[1]);
    }
    else // 子进程
    {
        // 关闭写端
        close(pipefd[1]);

        // 从管道读取数据
        char buffer[100];
        int n = read(pipefd[0], buffer, sizeof(buffer));
        if (n > 0)
            buffer[n] = 0;

        // 输出结果
        printf("Child received: %s\n", buffer);

        // 关闭读端
        close(pipefd[0]);
    }

    return 0;
}